# seed_test.py
from app import create_app, db
import sys
import traceback
from flask import current_app
from sqlalchemy import text, select, func # 导入 select, func

print(f"[seed_test] Python executable: {sys.executable}")
print(f"[seed_test] Imported db instance. ID: {id(db)}")

if __name__ == '__main__':
    print("[seed_test] Main block started.")
    # --- 保持 app/__init__.py 中手动设置 db.app = app ---
    app = create_app()
    print(f"[seed_test] App created. App object: {app}")
    print(f"[seed_test] App created. DB ID: {id(db)}")

    with app.app_context():
        print(f"\n[seed_test] Inside app_context. DB ID: {id(db)}")

        try:
            print("[seed_test] Importing User model inside context...")
            from app.models import User
            print(f"[seed_test] Model User imported successfully. Type: {type(User)}")
        except Exception as e:
            print(f"[seed_test] Error importing User model inside context: {e}")
            sys.exit(1)

        print("\n--- Diagnostics ---")
        try:
            print(f"[seed_test] current_app: {current_app.name}")
            db_app_attr = getattr(db, 'app', 'AttributeNotSet')
            print(f"[seed_test] db.app attribute: {db_app_attr}") # 应该显示 <Flask 'app'>
            print(f"[seed_test] db.engines: {db.engines}")
            default_engine = db.engine
            print(f"[seed_test] db.engine (default): {default_engine}")
            if default_engine is None:
                 print("[seed_test] CRITICAL: Could not get default engine via db.engine!")
                 sys.exit(1)
        except Exception as diag_e:
             print(f"[seed_test] Error during diagnostics: {diag_e}")
             sys.exit(1)
        print("--- End Diagnostics ---\n")

        # --- Attempt 1: Standard User.query.count() (仍可能失败) ---
        try:
            print("[seed_test] Attempt 1: Standard User.query.count()")
            user_count = User.query.count()
            print(f"[seed_test] Attempt 1 SUCCESSFUL. User count: {user_count}")
        except Exception as e1:
            print(f"[seed_test] Attempt 1 FAILED: {e1.__class__.__name__}: {e1}")
            # traceback.print_exc() # 可选

        # --- Attempt 2: 使用 db.session.execute + ORM select (无 bind) ---
        try:
            print("\n[seed_test] Attempt 2: Using db.session.execute(select(...)) (NO bind)")
            stmt = select(func.count(User.id)) # 构造 ORM 查询
            # 直接执行，让 scoped_session 自动找引擎
            result = db.session.execute(stmt)
            count = result.scalar_one()
            print(f"[seed_test] Attempt 2 SUCCESSFUL. User count: {count}")
        except Exception as e2:
            print(f"[seed_test] Attempt 2 FAILED: {e2.__class__.__name__}: {e2}")
            print("Traceback for Attempt 2:")
            traceback.print_exc()

        # --- Attempt 3: 使用 db.session.query() (无 bind) ---
        try:
            print("\n[seed_test] Attempt 3: Using db.session.query(User).count() (NO bind)")
            # 直接使用 session 的 query 方法
            count = db.session.query(User).count()
            print(f"[seed_test] Attempt 3 SUCCESSFUL. User count: {count}")
        except Exception as e3:
            print(f"[seed_test] Attempt 3 FAILED: {e3.__class__.__name__}: {e3}")
            print("Traceback for Attempt 3:")
            traceback.print_exc()

    print("\n[seed_test] Script finished.")
